-module(mnesia_op).
-include("agent.hrl").
-include_lib("stdlib/include/qlc.hrl").

-export([do/1]).
-export([insert/1]).
-export([delete/2]).
-export([delete/1]).
-export([lookup/2]).
-export([clear_table/1]).
-export([get_container/1]).
-export([get_cpu/1]).
-export([lookup_app/0]).
-export([get_pid/1]).
-export([get_agent_state/0]).
lookup_app() ->
	do(qlc:q([X || X <- mnesia:table(app)])).

lookup(app,Name) ->
	do(qlc:q([X || X <- mnesia:table(app), X#app.name =:= Name])).

get_pid(agent_state) ->
	do(qlc:q([X#agent_state.pid || X <- mnesia:table(agent_state), X#agent_state.id=:=0 ])).

get_container(agent_state) ->
	do(qlc:q([X#agent_state.container || X <- mnesia:table(agent_state), X#agent_state.id=:=0 ])).

get_cpu(agent_state) ->
	do(qlc:q([X#agent_state.cpu ||X <- mnesia:table(agent_state), X#agent_state.id=:=0  ])).
	
	
get_agent_state()->
	do(qlc:q([X ||X <- mnesia:table(agent_state) , X#agent_state.id=:=0 ])).

lookup_runtime_by_instance(AppName,ContainerName) ->
	do(qlc:q([X#instance_runtime.runtime||X<-mnesia:table(instance_runtime),X#instance_runtime.instance=:=#instance{container_name=ContainerName,app_name=AppName}])).

do(Q) ->
	F = fun() -> qlc:e(Q) end,
	{atomic, Val} = mnesia:transaction(F),
	Val.

insert(Rows) when is_list(Rows) ->
	F = fun() ->
			lists:foreach( fun mnesia:write/1, Rows)
		end,
		case mnesia:transaction(F) of
			{atomic, ok} ->
					ok;
			Any ->
				{error, Any}
		end;
insert(Row) ->
	case mnesia:transaction(fun()->mnesia:write(Row) end) of
			{atomic, ok} ->
					ok;
			Any ->
				{error, Any}
		end.
delete(Tab , Key) ->
	case mnesia:transaction(fun() -> mnesia:delete({Tab , Key}) end) of
				{atomic, ok} ->
						ok;
				{aborted, Reason} ->
						{error, Reason}
	end.

delete(Obj) ->
	case mnesia:transaction(fun() -> mnesia:delete_object(Obj) end) of
				{atomic, ok} ->
						ok;
				{aborted, Reason} ->
						{error, Reason}
	end.

clear_table(Tab) ->
	mnesia:clear_table(Tab).
